package com.gongyinlian.personalprofilewebsiteserver.common.exception;

import com.gongyinlian.personalprofilewebsiteserver.common.enums.ResultCode;
import com.gongyinlian.personalprofilewebsiteserver.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常处理器
 * 统一处理系统中的异常，返回标准的错误响应
 * 
 * @author personal-profile-website
 * @date 2024-10-27
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.error("业务异常: URI={}, Code={}, Message={}", 
                request.getRequestURI(), e.getCode(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理参数验证异常 - @Valid 校验失败
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.error("参数验证失败: URI={}", request.getRequestURI());
        
        // 获取第一个错误信息
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = fieldError != null ? fieldError.getDefaultMessage() : "参数验证失败";
        
        return Result.error(ResultCode.VALIDATE_FAILED.getCode(), message);
    }
    
    /**
     * 处理参数绑定异常 - @Validated 校验失败
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleBindException(BindException e, HttpServletRequest request) {
        log.error("参数绑定失败: URI={}", request.getRequestURI());
        
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = fieldError != null ? fieldError.getDefaultMessage() : "参数绑定失败";
        
        return Result.error(ResultCode.VALIDATE_FAILED.getCode(), message);
    }
    
    /**
     * 处理约束违反异常 - @Validated 单个参数校验失败
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
        log.error("约束违反: URI={}", request.getRequestURI());
        
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String message = violations.isEmpty() ? "参数验证失败" : 
                violations.iterator().next().getMessage();
        
        return Result.error(ResultCode.VALIDATE_FAILED.getCode(), message);
    }
    
    /**
     * 处理缺少请求参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleMissingServletRequestParameterException(
            MissingServletRequestParameterException e, HttpServletRequest request) {
        log.error("缺少请求参数: URI={}, Param={}", request.getRequestURI(), e.getParameterName());
        
        String message = String.format("缺少必需参数: %s", e.getParameterName());
        return Result.error(ResultCode.PARAM_NOT_COMPLETE.getCode(), message);
    }
    
    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleMethodArgumentTypeMismatchException(
            MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        log.error("参数类型不匹配: URI={}, Param={}, RequiredType={}", 
                request.getRequestURI(), e.getName(), e.getRequiredType());
        
        String message = String.format("参数 %s 类型错误", e.getName());
        return Result.error(ResultCode.PARAM_TYPE_ERROR.getCode(), message);
    }
    
    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Result<?> handleHttpRequestMethodNotSupportedException(
            HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.error("请求方法不支持: URI={}, Method={}", request.getRequestURI(), e.getMethod());
        
        String message = String.format("不支持 %s 请求方法", e.getMethod());
        return Result.error(ResultCode.METHOD_NOT_ALLOWED.getCode(), message);
    }
    
    /**
     * 处理404异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result<?> handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request) {
        log.error("404错误: URI={}, Method={}", request.getRequestURI(), e.getHttpMethod());
        
        return Result.error(ResultCode.NOT_FOUND.getCode(), "请求的资源不存在");
    }
    
    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常: URI={}", request.getRequestURI(), e);
        
        return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "系统内部错误");
    }
    
    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        log.error("非法参数: URI={}, Message={}", request.getRequestURI(), e.getMessage());
        
        return Result.error(ResultCode.BAD_REQUEST.getCode(), e.getMessage());
    }
    
    /**
     * 处理数据库异常
     */
    @ExceptionHandler({
        org.springframework.dao.DataAccessException.class,
        org.springframework.jdbc.BadSqlGrammarException.class
    })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> handleDatabaseException(Exception e, HttpServletRequest request) {
        log.error("数据库异常: URI={}", request.getRequestURI(), e);
        
        return Result.error(ResultCode.DATABASE_ERROR.getCode(), "数据库操作失败");
    }
    
    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        log.error("未知异常: URI={}, Message={}", request.getRequestURI(), e.getMessage(), e);
        
        // 开发环境返回详细错误信息，生产环境返回通用错误
        String message = "系统异常，请稍后再试";
        
        return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), message);
    }
}

